<%--
XPTracker - Alternative Agile Tracking Tool
Copyright (C) 2006-2009  Stephen Starkey

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
--%>
<%@ include file="/taglibs.jsp" %>
<c:set var="title" value="Planning" scope="request"/>
<s:layout-render name="/layout/normal.jsp">
  <s:layout-component name="htmlHead">
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/template.js"></script>
    
    <script type="text/javascript">
      var sizeToPoints = eval('${xp:jsFriendly(actionBean.sizeToPoints)}');
      var latestDestinationRequest = 0;
      var storyIds = [
          <c:forEach items="${actionBean.stories}" var="story" varStatus="stat">${story.id}${stat.last ? '' : ','}</c:forEach>
          ];

      function moveCheckboxValueChanged(checkbox, storyId, skipEstimates) {
        <c:if test="${actionBean.currentSource.reorderable}">
        $('order_' + storyId).disabled = checkbox.checked;
        </c:if>
        updateEstimates();
      }

      var estimateUpdateEnabled = true;

      function updateEstimates() {
        if (!estimateUpdateEnabled) {
          return;
        }

        var srcTotal = 0;
        var srcPointsTotal = 0;
        for (var i = 0; i < storyIds.length; i++) {
          if (!$('move_' + storyIds[i]).checked) {
            var estField = $('estimate_' + storyIds[i]);
            if (!estField.value) {
              estField.value = '0';
            } else {
              srcTotal += parseFloat(estField.value);
            }
            srcPointsTotal += sizeToPoints[$('size_' + storyIds[i]).value];
          }

          var estimate = $('estimate_' + storyIds[i]).value;
          var actual = $('effort_' + storyIds[i]).innerHTML;
          var remaining = estimate - actual;
          $('remaining_' + storyIds[i]).innerHTML = remaining;
        }
        $('src_estimate').innerHTML = srcTotal;
        $('src_points').innerHTML = srcPointsTotal;

        $('event').name = 'GetEstimate';
        latestDestinationRequest++;
        $('destinationRequest').value = latestDestinationRequest;
        $('dest_estimate').innerHTML = '<em>...</em>';
        $('dest_points').innerHTML = '<em>...</em>';
        var params = Form.serialize($('planningForm'));

        $('event').name = 'ApplyPlan';
        new Ajax.Updater('dest_est_holder', $('planningForm').action,
          {method:'post', postBody: params, onComplete: replaceEstimate});

      }

      function replaceEstimate(originalUpdate) {
        var value = $('dest_est_holder').innerHTML;
        var items = value.split(';');
        if (items[0] == latestDestinationRequest) {
          $('dest_estimate').innerHTML = items[1];
          $('dest_points').innerHTML = items[2];
        }
      }
    </script>
  </s:layout-component>
  <s:layout-component name="body">
    <s:form id="planningForm" beanclass="org.xptracker.web.PlanningActionBean">
      <input type="hidden" id="event" name="ApplyPlan" value="1"/>
      <input type="hidden" id="destinationRequest" name="destinationRequest"/>
      Source: <select style="margin-right: 10px">
      <c:forEach items="${actionBean.sources}" var="source">
        <c:if test="${curSourceType ne source.sourceType}">
          <optgroup label="${source.sourceType}">
          <c:set var="curSourceType" value="${source.sourceType}"/>
        </c:if>
        <option
            value="${source.id}"
            <c:if test="${source eq actionBean.currentSource}">selected="true"</c:if>
            onclick="switchTo(this)">
            ${source.name}
        </option>
        <c:if test="${curSourceType ne source.sourceType}">
          </optgroup>
        </c:if>
      </c:forEach>
    </select>
      Destination: <select name="destination" onchange="updateEstimates()">
      <c:forEach items="${actionBean.destinations}" var="destination">
        <c:if test="${curDestType ne destination.sourceType}">
          <optgroup label="${destination.sourceType}">
          <c:set var="curDestType" value="${destination.sourceType}"/>
        </c:if>
        <option value="${destination.id}"
            <c:if test="${destination eq actionBean.currentDestination}">selected="true"</c:if>> ${destination.name} </option>
        <c:if test="${curDestType ne destination.sourceType}">
          </optgroup>
        </c:if>
      </c:forEach>
    </select>
      <c:set var="idx" value="1"/>
      <div style="width: 250px; float:right; margin-top: 10px; border:1px dashed black; padding: 5px;">
        <table style="float:right">
          <tr>
            <td></td>
            <td class="center" >Points</td>
            <td></td>
            <td class="center" >Hours</td>
          </tr>
          <tr>
            <td>Source:</td>
            <td class="center" id="src_points"></td>
            <td>/</td>
            <td class="center" id="src_estimate"></td>
          </tr>
          <tr>
            <td>Destination:</td>
            <td class="center" id="dest_points"></td>
            <td>/</td>
            <td class="center" id="dest_estimate"></td>
          </tr>
        </table>
        <span style="display:none" id="dest_est_holder"></span>
        <ss:secure roles="planner">
          <span style="float:right">
            <s:submit name="Apply" value="Save Changes"/>
            <%--<input type="button" id="breakout_button" value="Task Breakout" onclick="displayTasks()"/>--%>
          </span>
        </ss:secure>
      </div>                                                                           
      <div style="width: 80%; margin-top: 10px; margin-right: 80px;">
      <script type="text/javascript">
        function toggleAll(enabled) {
          estimateUpdateEnabled = false;
          var inputFields = document.getElementsByTagName('input');
          for(var i = 0; i < inputFields.length; i++) {
            if (inputFields[i].name.match("move")) {
              inputFields[i].checked = enabled;
            }
          }
          estimateUpdateEnabled = true;
          updateEstimates();
        }

        var storyIds = [];
        var storySeverities = [];
        var storyTasks = new Object();
        function addStoryTask(storyId, taskId, taskSummary) {
          var taskList = storyTasks[storyId];
          if (taskList == null) {
            taskList = [];
            storyTasks[storyId] = taskList;
          }
          taskList.push([taskId, taskSummary]);
        }
      </script>

        <table style="display:none">
          <tbody id="rowTemplate">
            <tr class="+{severity}">
              <td colspan="2"><input type="hidden" name="tasks[+{index}].id" value="+{taskId}"/></td>
              <td colspan="3">
                <input type="text" name="tasks[+{index}].summary" size="120" value="+{taskSummary}"/>
              </td>
              <td>
                <input type="text" name="tasks[+{index}].estimate" size="4" onblur="syncStoryEstimate(+{storyId});"/>
              </td>
            </tr>
          </tbody>
        </table>

        <script type="text/javascript">
          var rowIndex = 0;
          var rowTemplate = TrimPath.parseTemplate($('rowTemplate').innerHTML);
          function addTaskRow(storyId, storySeverity, taskId, taskSummary) {
            var result = rowTemplate.process({index: rowIndex, storyId: storyId, severity: storySeverity, taskId: taskId,
                                              taskSummary: taskSummary});
            new Insertion.After('row_' + storyId, result);
            rowIndex++;
          }
        </script>

      <s:url beanclass="org.xptracker.web.PlanningActionBean" var="url" scope="request"/>

      <dt:table name="actionBean.stories" id="story" class="planning" style="width:90%" decorator="planningDecorator"
                requestURI="${url}" excludedParams="_sourcePage">
        <dt:column title="<input type='checkbox' onchange='toggleAll(this.checked)'/>" style="width:5%">
          <s:checkbox id="move_${story.id}" name="move[${story.id}]" value="true" onchange="moveCheckboxValueChanged(this, ${story.id})"/>
        </dt:column>
        <c:if test="${actionBean.currentSource.reorderable}">
          <dt:column title="Order" style="width:5%">
            <s:text id="order_${story.id}" name="order[${story.id}]" value="${idx}" size="2"/>
            <input type="hidden" name="old_order_${story.id}" value="${idx}" size="2"/>
            <c:set var="idx" value="${idx + 1}"/>
          </dt:column>
        </c:if>
        <dt:column title="Story"><span class="${story.size}" id="summary_size_${story.id}"><xp:story-link story="${story}"/></span></dt:column>
        <dt:column title="Customers">
          <c:forEach var="customer" items="${story.customers}" varStatus="stat">${customer}${stat.last ? '' : ', '}</c:forEach>
        </dt:column>
        <dt:column property="dueDate" title="Due" class="right" format="{0,date,M/d/yyyy}"  sortable="true" sortProperty="dueDate"/>
        <dt:column title="Severity" style="width: 80px;" sortable="true" sortProperty="severity">
            <xp:spinner enumClass="org.xptracker.domain.Severity" name="severity[${story.id}]" id="severity_${story.id}"
                      value="${story.severity}" keyPrefix="story.severity." onChange='updateSeverity("${story.id}")'/>
        </dt:column>
        <dt:column title="Size" style="width: 80px;" sortable="true" sortProperty="size">
            <xp:spinner enumClass="org.xptracker.domain.Size" name="size[${story.id}]" id="size_${story.id}"
                      value="${story.size}" keyPrefix="story.size." onChange='updateSize("${story.id}")'/>
        </dt:column>
        <dt:column title="Estimate" style="width:5%" sortable="true" sortProperty="estimate">
          <s:text id="estimate_${story.id}" name="estimate[${story.id}]" value="${story.estimate}" size="4" onblur="updateEstimates()"/>
          <script type="text/javascript">
            <%-- todo Add story tasks by constructing a map of story IDs to tasks --%>
            <%--<c:forEach items="${story.tasks}" var="task">--%>
                <%--addStoryTask(${story.id}, ${task.id}, '${xp:jsFriendly(task.summary)}');--%>
            <%--</c:forEach>--%>
            storyIds.push(${story.id});
            storySeverities.push('${story.severity}')
          </script>
        </dt:column>
        <dt:column title="Remaining" style="width:5%">
          <span id="remaining_${story.id}"></span>
          <span id="effort_${story.id}" style="display:none"><fmt:formatNumber value="${xp:fromMillis(story.totalEffort, 'hours')}" pattern="##.##"/></span>
        </dt:column>
      </dt:table>
      </div>
    </s:form>

    <script type="text/javascript">
      function displayTasks() {
        for (var i = 0; i < storyIds.length; i++) {
          var taskList = storyTasks[storyIds[i]];
          if (taskList != null) {
            for (var j = 0; j < taskList.length; j++) {
              addTaskRow(storyIds[i], storySeverities[i], taskList[j][0], taskList[j][1]);
            }
          }
        }
        Element.hide('breakout_button');
      }

      function switchTo(option) {
        $('switchSrc').value = option.value;
        $('switchForm').submit();
      }

      function updateSize(id) {
        $('summary_size_' + id).setAttribute('class', $('size_' + id).value);
        updateEstimates();
      }

      function updateSeverity(id) {
        $('row_' + id).setAttribute('class', $('severity_' + id).value);
      }
    </script>
    <s:form beanclass="org.xptracker.web.PlanningActionBean" style="display:none" id="switchForm" method="GET">
      <input type="hidden" id="switchSrc" name="src"/>
    </s:form>
    <script type="text/javascript">
      updateEstimates();
    </script>
  </s:layout-component>
</s:layout-render>